<?php

namespace App\Console\Commands;

use App\Service\KimiAIService;
use App\Service\ZhipuAIService;
use Illuminate\Console\Command;
use Illuminate\Redis\Connections\PhpRedisConnection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use GuzzleHttp\Promise;
use GuzzleHttp\Client;

class GetJobDataTwo extends Command
{
    protected $signature   = 'get:job-data-batch {--examtype=default_examtype} {--city=default_city} {--year=default_year} {--month=default_month}';
    protected $description = 'Individually update each job data record based on the given criteria';
    /** @var PhpRedisConnection redis */
    protected $redis; // Redis 实例
    protected $processingTypeKey = 'current_processing_type'; // Redis 键名，用于存储当前处理类型索引
    protected $jobLockKeyPrefix  = 'job_lock_batch_'; // Redis 锁的键名前缀
    protected $batchSize         = 5; // 每批处理的 job 数量

    public function __construct()
    {
        parent::__construct();

        // 连接到 Redis 服务器
        $this->redis = Cache::store('redis')->getStore()->connection();
    }

    public function handle()
    {
        // $chatService = new ZhipuAIService();
        // $result = $chatService->chat([
        //     "messages"    => [
        //         [
        //             "role"    => "user",
        //             "content" => '你是',
        //         ]
        //     ],
        //     "temperature" => 0.6,
        //     "model"=>'GLM-4-Flash'
        // ]);
        ini_set('memory_limit', -1);
        set_time_limit(-1);

        // 获取传入的参数
        $examtype = $this->option('examtype');
        $city = $this->option('city');
        $year = $this->option('year');
        $month = $this->option('month');

        // 构建查询
        $query = DB::table('jobs');

        if ($examtype !== 'default_examtype') {
            $query->where('examtype', $examtype);
        }

        if ($city !== 'default_city') {
            $query->where('city', $city);
        }

        if ($year !== 'default_year') {
            $query->whereYear('pubdate', $year);
        }

        if ($month !== 'default_month') {
            $query->whereMonth('pubdate', $month);
        }

        $query->select(['id', 'info', 'result'])->where('status', 0)->where('id','>',2076);

        // 获取符合条件的数据
        $jobs = $query->orderBy('id', 'asc')->limit(20)->get();

        $updatedCount = 0;
        // Process jobs in batches
        foreach ( $jobs->chunk($this->batchSize) as $jobChunk ) {
            $promises = [];
            foreach ( $jobChunk as $job ) {
                // Create a promise for each job
                $promises[] = $this->processJob($job);
            }
            dd($promises);
            // 等待所有 Promise 完成
            $results = Promise\Utils::all($promises)->wait();

            // foreach ( $results as $index => $result ) {
            //     $job = $jobChunk[$index];
            //     if ($result['state'] === 'fulfilled') {
            //         $data = $result['value'];
            //         if ($data['update']) {
            //             $updatedCount++;
            //             $this->info("Record with ID {$job->id} has been updated with type '{$data['type']}'.");
            //         } else {
            //             $this->error("Failed to update record with ID {$job->id}.");
            //         }
            //     } else {
            //         $this->error("Failed to process job ID {$job->id}: ".$result['reason']);
            //     }
            // }
        }

        $this->info("Total {$updatedCount} record(s) have been updated.");
    }

    private function processJob($job)
    {
        return function () use ($job) {
            $result = null;
            $updateData = [];
            $success = false;

            try {
                if (! $job->info || $job->result) {
                    return ['update' => false];
                }

                // 构建当前 job 的锁键名
                $jobLockKey = $this->jobLockKeyPrefix.$job->id;

                // 尝试获取锁
                $lockAcquired = $this->redis->set($jobLockKey, 1, 'EX', 60 * 3, 'NX');

                if (! $lockAcquired) {
                    return ['update' => false];
                }

                // 获取当前处理类型索引并递增
                // $processingTypeIndex = $this->redis->incr($this->processingTypeKey);
                // // 计算当前处理类型
                // $typeList = ['zhipu', 'kimi', 'yuejin', 'hailuo'];
                // $typeIndex = $processingTypeIndex % count($typeList);
                // $type = $typeList[$typeIndex];
                $type='zhipu_fast';
                // 获取结果并更新数据库
                $chatService = (new ZhipuAIService());
                $result = $chatService->chat([
                    "messages"    => [
                        ["role" => "user", "content" => $this->buildPrompt($job->info)]
                    ],
                    "temperature" => 0.6,
                ]);

                $updateData = [
                    'type'   => $type,
                    'status' => ! empty($result) ? 1 : -1,
                    'result' => ! empty($result) ? json_encode($result, JSON_UNESCAPED_UNICODE) : null,
                ];

                $updateResult = DB::table('jobs')
                                  ->where('id', $job->id)
                                  ->update($updateData);

                if ($updateResult) {
                    $success = true;
                }

                // 释放锁
                $this->redis->del($jobLockKey);

            } catch (\Throwable $exception) {
                $this->error("Failed to process job ID {$job->id}: ".$exception->getMessage());
            }

            return ['update' => $success, 'type' => $type];
        };
    }

    private function buildPrompt($content)
    {
        return <<<temp
请从招聘公告内容提取以下信息，请你认真去理解招聘公告的信息，请用中文回答我的内容，其中笔试时间、面试时间、成绩查询时间如果存在具体的时间，统一的时间格式为：2024-01-14这样的格式，招考人数如果存在确定的就显示为数字，面试比例如果可以确定的话只显示具体比列就可以了，提取到的所有信息将其以JSON格式返回，其中key使用英文标识,返回结果禁止出现markdown语法相关的标签：
- **笔试时间**：提取公告中的考试日期。
- **笔试内容**：提取公告中描述的笔试内容。
- **面试时间**：提取公告中的面试日期。
- **面试内容**：提取公告中描述的面试内容。
- **成绩查询时间**：提取公告中提到的成绩查询时间。
- **面试比例**：提取公告中提到的面试比例。
- **招考人数**：提取公告中提到的招考人数。
将这些信息整理成如下格式的JSON数组，并填入指定的key：
{
  "exam_date": "提取的笔试时间",
  "exam_content": "提取的笔试内容",
  "interview_date": "提取的面试时间",
  "interview_content": "提取的面试内容",
  "results_query_date": "提取的成绩查询时间",
  "interview_ratio": "提取的面试比例",
  "user_num": "提取的招考人数"
}
招聘公告内容如下:

{$content}
temp;
    }
}
